<template>
  <div class="rule_index_wrapper">
    <div v-show="currentBanner==='list'">
      <a-card>
        <a-form layout="inline">
          <a-form-item>
            <a-input
              style="width:280px;
                font-size:14px;
                font-family:Microsoft YaHei;
                color:rgba(190,194,201,1)"
              placeholder="请输入规则名称或者最后修改人名称"
              v-model="ruleQueryCondition.queryText"
            >
              <a-icon slot="suffix" type="search" />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-select placeholder="请选择规则类型" v-model="ruleQueryCondition.type" style="width:240px;">
              <a-select-option
                :value="item.value"
                :key="item.value"
                v-for="item in [
                  {label:'一致性',value:'1'},
                  {label:'完整性',value:'2'},
                  {label:'及时性',value:'3'},
                  {label:'规范性',value:'4'}
                ]"
              >{{ item.label }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-select placeholder="状态" v-model="ruleQueryCondition.enabled" style="width:240px;">
              <a-select-option
                :value="item.value"
                :key="item.value"
                v-for="item in [{label:'启用',value:'Y'},{label:'不启用',value:'N'}]"
              >{{ item.label }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button
              style="margin-left: 30px;"
              @click="handleRuleSearch"
              icon="search"
              type="primary"
            >查询</a-button>
            <a-button
              style="margin-left: 30px;"
              @click="()=>{this.ruleQueryCondition={};this.handleRuleSearch()}"
              icon="sync"
            >重置</a-button>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card style="margin-top: 22px;">
        <a-button
          style="margin-bottom: 12px;"
          @click="handleRuleCreate"
          type="primary"
          icon="plus"
        >新增</a-button>
        <a-table
          rowKey="id"
          :data-source="rules"
          :pagination="rulePagination"
          @change="handleRulePageChange"
          :loading="ruleLoading"
          :columns="ruleColumnTitles"
        >
          <template
            v-for="item in ['name','description','weight','formulaName','lastUpdateByUserName','execCount']"
            slot-scope="text"
            :slot="item"
          >{{ text }}</template>
          <template slot="enabled" slot-scope="text">{{ text==='Y'?'启用':'不启用' }}</template>
          <template slot="type" slot-scope="text">{{ ruleTypeLabel[text] }}</template>
          <template
            v-for="item in ['lastUpdateByUserName']"
            slot-scope="text"
            :slot="item"
          >{{ text }}</template>
          <template slot="nextExecTime" slot-scope="text">{{ text?text: nextExecTime }}</template>
          <template slot="option" slot-scope="text,record,index">
            <a-button
              type="link"
              size="small"
              style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
              @click="()=>handleShowRule(record,index)"
            >详情</a-button>
            <a-button
              type="link"
              size="small"
              style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
              @click="()=>handleRuleEdit(record,index)"
            >编辑</a-button>
            <a-button
              type="link"
              size="small"
              style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
              :disabled="!record.formulaId||!record.formula||!record.formula.id||!record.formula.name"
              @click="()=>handleRuleTest(record,index)"
            >测试</a-button>
            <!-- <a-button
            type="link"
            size="small"
            style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
            @click="()=>handleRuleEdit(record,index)"
            >更多</a-button>-->
            <a-dropdown>
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-button
                    type="link"
                    size="small"
                    style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
                    :disabled="!record.formulaId||!record.formula||!record.formula.id||!record.formula.name"
                    v-loading="record.runLoading"
                    @click="()=>handleRuleRun(record,index)"
                  >手动执行</a-button>
                  <!-- <a href="javascript:;">手动执行</a> -->
                </a-menu-item>
                <a-menu-item>
                  <a-button
                    type="link"
                    size="small"
                    style="
              height:15px;
              font-size:12px;
              font-family:Microsoft YaHei;
              font-weight:400;"
                    @click="()=>handleCopyRule(record,index)"
                  >复制</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button
                    :disabled="!record.formulaId||!record.formula||!record.formula.id||!record.formula.name"
                    type="link"
                    size="small"
                    style="
                    height:15px;
                    font-size:12px;
                    font-family:Microsoft YaHei;
                    font-weight:400;"
                    @click="()=>handleDisableRule(record,index)"
                  >{{ record.enabled==='Y' ? '禁用' : '启用' }}</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm
                    title="确认删除?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="()=>handleDeleteRule(record)"
                  >
                    <a-button
                      size="small"
                      style="
                    height:15px;
                    font-size:12px;
                    font-family:Microsoft YaHei;
                    font-weight:400;
                    color:#ff4d4f;
                  "
                      type="link"
                    >删除</a-button>
                  </a-popconfirm>
                  <!-- <a-button
                    type="link"
                    size="small"
                    style="
                    height:15px;
                    font-size:12px;
                    font-family:Microsoft YaHei;
                    font-weight:400;"
                    @click="()=>handleDeleteRule(record,index)"
                  >删除</a-button>-->
                </a-menu-item>
                <!-- <a-menu-item>
                <a href="javascript:;">删除</a>
                </a-menu-item>-->
              </a-menu>
            </a-dropdown>
          </template>
        </a-table>
      </a-card>
    </div>

    <a-card v-show="currentBanner==='edit'">
      <a-col style="text-align:right">
        <a-button style="margin-right:20px" @click="()=>currentBanner='list'">返回</a-button>
        <a-button style="margin-right:20px" type="primary" @click="handleRuleEditReset">重置</a-button>
        <a-button
          style="margin-right:20px"
          type="primary"
          v-loading="ruleEditLoading"
          @click="handleRuleSave"
        >提交</a-button>
        <a-button
          style="margin-right:20px"
          type="primary"
          :disabled="!ruleEdit.formula||!ruleEdit.formula.id"
          @click="handleRuleEditTest"
        >测试</a-button>
      </a-col>
      <br />
      <a-form-model
        :labelCol="{span:4}"
        :wrapperCol="{span:14}"
        :rules="ruleEditValidateRule"
        ref="ruleEditFormRef"
        :model="ruleEdit"
      >
        <a-form-model-item ref="name" label="规则名称" prop="name">
          <a-input style="width: 240px;" placeholder="请输入规则名称" v-model="ruleEdit.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="规则类型" prop="type">
          <a-select v-model="ruleEdit.type" style="width:240px;" placeholder="规则类型">
            <a-select-option
              :value="item.value"
              :key="item.value"
              v-for="item in [
                {label:'一致性',value:'1'},
                {label:'完整性',value:'2'},
                {label:'及时性',value:'3'},
                {label:'规范性',value:'4'}
              ]"
            >{{ item.label }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item prop="weight" label="规则权重">
          <a-input placeholder="请输入规则权重" style="width:240px" v-model="ruleEdit.weight"></a-input>
        </a-form-model-item>
        <a-form-model-item prop="description" label="规则描述">
          <a-textarea
            placeholder="请选择规则描述"
            style="width:600px;height:80px;"
            v-model="ruleEdit.description"
          ></a-textarea>
        </a-form-model-item>
        <a-form-model-item prop="enabled" label="状态">
          <!-- <a-checkbox
            :checked="ruleEdit.enabled==='Y'"
            @change="e=>ruleEdit.enabled = (e.target.checked) ? 'Y' : 'N'"
          ></a-checkbox>-->
          <a-switch
            style="width: 70px;"
            checkedChildren=" 启用"
            unCheckedChildren="不启用"
            :checked="ruleEdit.enabled==='Y'"
            @change="checked=>ruleEdit.enabled = checked?'Y':'N'"
          ></a-switch>
        </a-form-model-item>
        <a-form-model-item prop="formulaId" label="绑定公式">
          <a-select
            show-search
            style="width:240px"
            :value="currentFormula.name"
            placeholder="请输入公式名称"
            :filter-option="false"
            :not-found-content="formulaChoose.fetching ? undefined : null"
            @search="handleQueryFormula"
            @change="handleFormulaChange"
          >
            <a-spin v-if="formulaChoose.fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="d in formulaChoose.rows" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
          <span
            style="font-size:12px;
          font-family:Microsoft YaHei;
          font-weight:400;"
          >
            找不到匹配的公式?
            <a-button
              style="font-size:12px;
            font-family:Microsoft YaHei;
            font-weight:400;"
              @click="handleAddForumal"
              type="link"
            >点此新增</a-button>
          </span>
          <!-- <a-select v-model="ruleEdit.formula.name" placeholder="请输入公式名称进行查询"></a-select> -->
          <a-descriptions
            bordered
            :column="1"
            style="
          background:rgba(247,248,251,1);
          border:1px solid rgba(228,231,238,1);"
          >
            <a-descriptions-item label="描述">{{ currentFormula.description }}</a-descriptions-item>
            <a-descriptions-item label="总记录查询">{{ currentFormula.allCountSql }}</a-descriptions-item>
            <a-descriptions-item label="异常记录查询">{{ currentFormula.errDataSql }}</a-descriptions-item>
            <a-descriptions-item label="得分计算">{{ currentFormula.passCountSql }}</a-descriptions-item>
          </a-descriptions>
        </a-form-model-item>
        <a-form-model-item label="配置公式参数">
          <a-table
            rowKey="paramName"
            :columns="[
              {title:'参数名',dataIndex:'paramName',key:'paramName'},
              {title:'数据库',dataIndex:'dbName',key:'dbName',scopedSlots:{customRender:'dbName'}},
              {title:'表名',dataIndex:'tableName',key:'tableName',scopedSlots:{customRender:'tableName'}},
              {title:'列名',dataIndex:'columnName',key:'columnName',scopedSlots:{customRender:'columnName'}},
              {title:'操作',dataIndex:'_option',key:'option',scopedSlots:{customRender:'option'}},
            ]"
            :data-source="ruleEdit.binds"
          >
            <template
              v-for="item in ['dbName','tableName','columnName']"
              slot-scope="text,record"
              :slot="item"
            >
              <a-input
                :key="item"
                :value="text"
                @change="e=> handleDataChange(record,item,e.target.value)"
              ></a-input>
            </template>
            <template slot="option" slot-scope="text,record,index">
              <a-button type="link" @click="()=>handleParamCopy(index)" :disabled="index===0">复制上一行</a-button>
              <a-button type="link" @click="()=>handleClearParamRow(index,record)">重置</a-button>
            </template>
          </a-table>
        </a-form-model-item>
      </a-form-model>
    </a-card>

    <a-card v-show="currentBanner==='view'">
      <a-col style="text-align:right">
        <a-button style="margin-right:20px" @click="()=>currentBanner='list'">返回</a-button>
        <!-- <a-button style="margin-right:20px" type="primary" :disabled="!ruleEdit.formula||!ruleEdit.formula.id" v-loading="ruleEdit.runLoading" @click="()=>handleRuleRun(ruleEdit)">执行</a-button> -->
        <a-button
          style="margin-right:20px"
          type="primary"
          v-loading="ruleEditLoading"
          @click="()=>{handleRuleEdit(ruleShow);currentBanner='edit'}"
        >编辑</a-button>
        <a-button
          style="margin-right:20px"
          type="primary"
          :disabled="!ruleShow.formula||!ruleShow.formula.id"
          v-loading="ruleShow.testLoading"
          @click="handleRuleShowTest"
        >测试</a-button>
        <a-button
          style="margin-right:20px"
          type="primary"
          :disabled="!ruleShow.formula||!ruleShow.formula.id"
          v-loading="ruleShow.runLoading"
          @click="handleRuleShowRun"
        >手动执行</a-button>
      </a-col>
      <a-form style="line-height:20px" bordered :labelCol="{span:4}" :wrapperCol="{span:20}">
        <a-form-item style="height:15px;" label="规则名称">{{ ruleShow.name }}</a-form-item>
        <a-form-item style="height:15px;" label="规则描述">{{ ruleShow.description }}</a-form-item>
        <a-form-item style="height:15px" label="规则权重">{{ ruleShow.weight }}</a-form-item>
        <a-form-item label="绑定公式">
          {{ currentFormula.name }}
          <a-descriptions
            bordered
            :column="1"
            size="small"
            style="
          background:rgba(247,248,251,1);
          border:1px solid rgba(228,231,238,1);"
          >
            <a-descriptions-item label="描述">{{ currentFormula.description }}</a-descriptions-item>
            <a-descriptions-item label="总记录查询">{{ currentFormula.allCountSql }}</a-descriptions-item>
            <a-descriptions-item label="异常记录查询">{{ currentFormula.errDataSql }}</a-descriptions-item>
            <a-descriptions-item label="得分计算">{{ currentFormula.passCountSql }}</a-descriptions-item>
          </a-descriptions>
        </a-form-item>
        <a-form-item>
          <a-tabs style="margin-left:15%;width:100%" type="card" @change="handleTabChange">
            <a-tab-pane key="1" tab="参数信息">
              <a-table
                rowKey="paramName"
                :columns="[
                  {title:'参数名',dataIndex:'paramName',key:'paramName'},
                  {title:'数据库',dataIndex:'dbName',key:'dbName',scopedSlots:{customRender:'dbName'}},
                  {title:'表名',dataIndex:'tableName',key:'tableName',scopedSlots:{customRender:'tableName'}},
                  {title:'列名',dataIndex:'columnName',key:'columnName',scopedSlots:{customRender:'columnName'}},
                ]"
                :data-source="ruleShow.binds"
              ></a-table>
            </a-tab-pane>
            <a-tab-pane key="2" tab="执行记录">
              <a-table
                rowKey="id"
                :pagination="ruleExecHistoryPage"
                @change="handleRuleExecHistoryPageChange"
                :columns="[
                  {title:'执行时间',dataIndex:'execTime',key:'execTime'},
                  {title:'医院',dataIndex:'orgName',key:'orgName'},
                  {title:'数据批次',dataIndex:'batchNo',key:'batchNo'},
                  {title:'总数据',dataIndex:'total',key:'total'},
                  {title:'异常数据',dataIndex:'errorCount',key:'errorCount'}
                ]"
                :data-source="ruleExecHistory"
              ></a-table>
            </a-tab-pane>
          </a-tabs>
        </a-form-item>
      </a-form>
    </a-card>
    <!-- </a-modal> -->
    <a-modal
      :footer="null"
      :zIndex="1100"
      :bodyStyle="{'overflow-y':'scroll'}"
      v-model="ruleRun.visible"
      width="688px"
      title="执行明细"
    >
      <a-descriptions bordered :column="1" size="small">
        <a-descriptions-item label="总记录查询">{{ ruleRun.allCountSql }}</a-descriptions-item>
        <a-descriptions-item label="异常记录查询">{{ ruleRun.errDataSql }}</a-descriptions-item>
        <a-descriptions-item label="得分计算">{{ ruleRun.passCountSql }}</a-descriptions-item>
      </a-descriptions>

      <a-spin :spinning="ruleRun.loading">
        <a-descriptions
          :column="1"
          style="
          margin-top:20px;
          background:rgba(247,248,251,1);
          border:1px solid rgba(228,231,238,1);"
        >
          <a-descriptions-item label="执行完成">{{ ruleRun.execTime }}</a-descriptions-item>
          <a-descriptions-item label="总数">{{ ruleRun.allCount }}</a-descriptions-item>
          <a-descriptions-item label="异常数">{{ ruleRun.errorCount }}</a-descriptions-item>
          <a-descriptions-item label="得分">{{ ruleRun.ruleScore }}</a-descriptions-item>
        </a-descriptions>
        <!-- </a-spin> -->
        <!-- <a-spin :spinning="ruleRun.loading">
        <div>转圈圈</div>
        </a-spin>-->
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import { deleteRule, queryRules, saveRule, queryExecHistory, changeEnabled } from '@/api/rule'
import { execOneRule, execTest } from '@/api/rule-exector'
import { listFormulaLines, queryFormulaWithLines } from '@/api/formula'
import { getConfigByKey } from '@/api/system'
import { deepCopy } from '@/utils/util'
export default {
  name: 'Rule',
  components: {},
  computed: {
    isEditRuleEnabled: function () {
      return this.ruleEdit.enabled === 'Y'
    }
  },
  data: function () {
    return {
      // 控制显示
      currentBanner: 'list',
      nextExecTime: null,
      ruleTypeLabel: {
        1: '一致性',
        2: '完整性',
        3: '及时性',
        4: '规范性'
      },
      // 表结构
      ruleColumnTitles: [
        {
          title: '规则名称',
          dataIndex: 'name',
          ellipsis: true,
          width: 150,
          key: 'name'
          // scopedSlots: { customRender: 'name' }
        },
        {
          title: '规则类型',
          width: 150,
          dataIndex: 'type',
          key: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '规则权重',
          width: 100,
          dataIndex: 'weight',
          key: 'weight',
          scopedSlots: { customRender: 'weight' }
        },
        {
          title: '规则描述',
          ellipsis: true,
          dataIndex: 'description',
          key: 'description',
          scopedSlots: { customRender: 'description' }
        },
        {
          title: '绑定公式',
          ellipsis: true,
          dataIndex: 'formula.name',
          key: 'formula.name',
          scopedSlots: { customRender: 'formulaName' }
        },
        {
          title: '最后修改时间',
          ellipsis: true,
          dataIndex: 'lastUpdateTime',
          key: 'lastUpdateTime',
          scopedSlots: { customRender: 'lastUpdateTime' }
        },
        {
          title: '最后修改人',
          ellipsis: true,
          dataIndex: 'lastUpdateByUserName',
          key: 'lastUpdateByUserName',
          scopedSlots: { customRender: 'lastUpdateByUserName' }
        },
        {
          title: '是否启用',
          dataIndex: 'enabled',
          key: 'enabled',
          scopedSlots: { customRender: 'enabled' }
        },
        {
          title: '已执行次数',
          dataIndex: 'execCount',
          key: 'execCount',
          scopedSlots: { customRender: 'execCount' }
        },
        {
          title: '下次执行时间',
          ellipsis: true,
          dataIndex: 'nextExecTime',
          key: 'nextExecTime',
          scopedSlots: { customRender: 'nextExecTime' }
        },
        {
          title: '操作',
          key: 'option',
          width: 200,
          scopedSlots: { customRender: 'option' }
        }
      ],
      ruleQueryCondition: {
        queryText: undefined,
        type: undefined,
        enabled: undefined
      },
      ruleLoading: false,
      rules: [],
      rulePagination: {
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30', '40', '50'], // 每页数量选项
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: total => `共 ${total} 条记录` // 显示总数
      },
      ruleEditLoading: false,
      // ruleEditVisible: false,
      currentFormula: {
        allCountSql: undefined,
        passCountSql: undefined,
        errDataSql: undefined,
        name: undefined,
        description: undefined
      },
      ruleEdit: {
        name: null,
        type: null,
        enabled: 'Y',
        weight: null,
        formula: {},
        binds: []
      },
      ruleEditValidateRule: {
        name: [{ required: true, message: '请输入规则名' }],
        type: [{ required: true, message: '请选择规则类型' }],
        weight: [{ required: true, message: '请输入权重' }, {
          message: '请输入最多两位小数的正数',
          validator: (source, value, callback) => {
            const reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
            const f = reg.test(value)
            return f && parseFloat(value) >= 0.01
          }
        }],
        formulaId: [{ required: true, message: '请选择公式' }]
      },
      formulaChoose: {
        fetching: false,
        rows: [],
        map: {}
      },
      ruleShow: {},
      ruleExecHistory: [],
      ruleExecHistoryPage: {
        current: 1,
        pageSize: 5,
        total: 0
      },
      ruleRun: {
        visible: false,
        loading: false,
        allCountSql: null,
        allCount: null,
        passCountSql: null,
        passCount: null,
        errDataSql: null,
        errCount: null
      },
      ruleRunOneLoading: false
    }
  },
  created: function () {
    this.doRuleQuery()
    this.getNextExecTime()
  },
  methods: {
    handleTabChange: function (key) {},
    handleRuleExecHistoryPageChange: function (pagination) {
      this.ruleExecHistoryPage = pagination
      this.handleRuleExecResultQuery()
    },
    handleRuleExecResultQuery: function () {
      queryExecHistory(
        { ruleId: this.ruleShow.id },
        this.ruleExecHistoryPage.current,
        this.ruleExecHistoryPage.pageSize
      ).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        this.ruleExecHistoryPage.total = res.data.total
        this.ruleExecHistory = res.data.rows
        this.ruleExecHistoryPage.current = res.data.pageNum
        this.ruleExecHistoryPage.pageSize = res.data.pageSize
      })
    },
    handleFormulaChange: function (id) {
      const formula = this.formulaChoose.map[id]
      this.setCurrentFormulaSql(formula.lines)
      this.currentFormula.description = formula.description
      this.currentFormula.name = formula.name
      this.currentFormula.id = formula.id
      this.ruleEdit.formula = formula
      this.ruleEdit.formulaId = formula.id
      const binds = []
      if (formula.params) {
        formula.params.forEach(e => {
          binds.push({
            ruleParamId: e.id,
            paramName: e.name
          })
        })
      }
      this.ruleEdit.binds = binds
    },
    handleQueryFormula: function (name) {
      if (!name || name === '') {
        return
      }
      this.formulaChoose.fetching = true
      queryFormulaWithLines({ name })
        .then(res => {
          if (res.code === 200) {
            if (res.data.rows) {
              res.data.rows.forEach(e => {
                this.formulaChoose.map[e.id] = e
              })
            }
            this.formulaChoose.rows = res.data.rows
          }
        })
        .finally(() => {
          this.formulaChoose.fetching = false
        })
    },
    getNextExecTime: function () {
      getConfigByKey({ key: 'val.exec.time' }).then(res => {
        const date = new Date()
        this.nextExecTime =
          date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1) + ' ' + res.data.configValue
      })
    },
    /**
     * 将第index-1行的数据复制到index行
     */
    handleParamCopy: function (index) {
      const preRow = deepCopy(this.ruleEdit.binds[index - 1])
      for (let i = 0; i < this.ruleEdit.binds.length; i++) {
        if (i === index) {
          this.ruleEdit.binds[i].dbName = preRow.dbName
          this.ruleEdit.binds[i].tableName = preRow.tableName
          this.ruleEdit.binds[i].columnName = preRow.columnName
          break
        }
      }
    },
    /**
     * 清空第index行的数据
     * @param index 数据的array index
     * @param record 当前行obj
     */
    handleClearParamRow: function (index, record) {
      for (let i = 0; i < this.ruleEdit.binds.length; i++) {
        if (i === index) {
          this.ruleEdit.binds[i].dbName = null
          this.ruleEdit.binds[i].tableName = null
          this.ruleEdit.binds[i].columnName = null
          break
        }
      }
    },
    /**
     * 修改data中data[key]的值为value
     */
    handleDataChange: function (data, key, value) {
      this.$set(data, key, value)
    },
    /**
     * 用户主动搜索
     */
    handleRuleSearch: function () {
      this.rulePagination.current = 1
      this.doRuleQuery()
    },
    /**
     * 页码,页面尺寸修改
     */
    handleRulePageChange: function (pagination) {
      this.rulePagination = pagination
      this.doRuleQuery()
    },
    /**
     * 查询规则值,更新界面
     */
    doRuleQuery: function () {
      this.ruleLoading = true
      queryRules(this.ruleQueryCondition, this.rulePagination.current, this.rulePagination.pageSize)
        .then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          this.rulePagination.total = res.data.total
          this.rules = res.data.rows
          const queryPageNum = this.rulePagination.current
          this.rulePagination.current = res.data.pageNum
          this.rulePagination.pageSize = res.data.pageSize
          if (queryPageNum > 1 && (res.data.rows == null || res.data.rows.length === 0)) {
            this.rulePagination.current = 1
            this.doRuleQuery()
          }
        })
        .finally(() => {
          this.ruleLoading = false
        })
    },
    handleRuleCreate: function () {
      this.ruleEdit = {
        name: null,
        type: undefined,
        enabled: 'Y',
        weight: null,
        formula: {},
        binds: []
      }
      this.currentFormula = {
        allCountSql: null,
        passCountSql: null,
        errDataSql: null,
        name: undefined,
        description: null
      }
      this.currentBanner = 'edit'// = true
    },
    /**
     * 保存rule
     */
    handleRuleSave: function () {
      this.$refs.ruleEditFormRef.validate(valid => {
        if (!valid) {
          this.$message.error('参数输入有误')
        } else {
          this.ruleEditLoading = true
          const postData = deepCopy(this.ruleEdit)
          postData.formula = this.currentFormula
          postData.formulaId = this.currentFormula.id
          saveRule(postData).then(res => {
            if (res.code !== 200) {
              this.$message.error(res.message)
              return
            }
            this.currentBanner = 'list'
            this.doRuleQuery()
          }).finally(() => {
            this.ruleEditLoading = false
          })
        }
      })
    },
    // doRuleSave: function () { },
    handleShowRule: function (record, index) {
      // this.ruleShow = deepCopy(record)
      const row = deepCopy(record)
      if (record.formula == null || record.formula.id == null) {
        this.currentFormula = {}
      } else {
        listFormulaLines({ formulaId: record.formula.id }).then(res => {
          if (res.data) {
            this.setCurrentFormulaSql(res.data)
          }
        })
        this.currentFormula.description = row.formula.description
        this.currentFormula.name = row.formula.name
        this.currentFormula.id = row.formula.id
      }
      this.ruleShow = row
      this.ruleExecHistoryPage.total = 0
      this.ruleExecHistory = []
      this.ruleExecHistoryPage.current = 1
      this.handleRuleExecResultQuery()
      this.currentBanner = 'view'
    },
    handleRuleShowRun: function () {
      this.handleRuleRun(this.ruleShow)
    },
    handleRuleRun: function (record) {
      this.$set(record, 'runLoading', true)
      this.runLoading = true
      execOneRule({ ruleId: record.id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        this.$message.success(res.message)
        this.doRuleQuery()
      }).finally(() => { this.$set(record, 'runLoading', false) })
    },
    handleRuleShowTest: function () {
      this.handleRuleTest(this.ruleShow)
    },
    handleRuleEditReset: function () {
      const reset = {
        name: null,
        type: undefined,
        enabled: 'Y',
        id: this.ruleEdit.id,
        weight: null,
        formula: {},
        binds: []
      }
      this.ruleEdit = reset
      this.currentFormula = {
        allCountSql: null,
        passCountSql: null,
        errDataSql: null,
        name: undefined,
        description: null
      }
      // this.currentBanner = 'edit'// = true
    },
    handleRuleEditTest: function () {
      this.ruleRun = {
        visible: true,
        loading: true,
        allCountSql: this.currentFormula.allCountSql,
        allCount: null,
        passCountSql: this.currentFormula.passCountSql,
        passCount: null,
        errDataSql: this.currentFormula.errDataSql,
        errCount: null,
        binds: this.ruleEdit.binds
      }
      this.doExecTest({
        rule: {
          allCountSql: this.currentFormula.allCountSql,
          passCountSql: this.currentFormula.passCountSql,
          errorDataSql: this.currentFormula.errDataSql,
          binds: this.ruleEdit.binds
        }
      }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        this.setExexTestResult(res.data, this.ruleRun)
      }).finally(() => {
        this.ruleRun.loading = false
      })
    },
    handleRuleTest: function (record, index) {
      this.ruleRun = {
        visible: true,
        loading: true,
        allCountSql: null,
        allCount: null,
        passCountSql: null,
        passCount: null,
        errDataSql: null,
        errCount: null,
        binds: record.binds
      }
      listFormulaLines({ formulaId: record.formula.id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        res.data.forEach(e => {
          if (e.type === 'score') {
            this.ruleRun.allCountSql = e.sql1
            this.ruleRun.passCountSql = e.sql2
          } else if (e.type === 'error_result') {
            this.ruleRun.errDataSql = e.sql1
          }
        })
        this.doExecTest({
          rule: {
            allCountSql: this.ruleRun.allCountSql,
            passCountSql: this.ruleRun.passCountSql,
            errorDataSql: this.ruleRun.errDataSql,
            binds: this.ruleRun.binds
          }
        }).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          this.setExexTestResult(res.data, this.ruleRun)
          console.log(this.ruleRun)
        })
      }).finally(() => {
        this.ruleRun.loading = false
      })
    },
    doExecTest: function (testData) {
      console.log(testData)
      return execTest(testData)
    },
    setExexTestResult: function (source, to) {
      to.passCount = source.passDatCount
      to.execTime = source.execTime
      to.errorCount = source.errorDataCount
      to.ruleScore = source.ruleScore
      to.allCount = source.dataCount
    },
    handleRuleEdit: function (record, index) {
      const row = deepCopy(record)
      if (record.formula == null || record.formula.id == null) {
        this.currentFormula = {}
      } else {
        listFormulaLines({ formulaId: record.formula.id }).then(res => {
          if (res.data) {
            this.setCurrentFormulaSql(res.data)
          }
        })
        this.currentFormula.description = row.formula.description
        this.currentFormula.name = row.formula.name
        this.currentFormula.id = row.formula.id
      }
      this.ruleEdit = row
      this.currentBanner = 'edit'
    },
    setCurrentFormulaSql: function (line) {
      line.forEach(e => {
        if (e.type === 'score') {
          this.currentFormula.allCountSql = e.sql1
          this.currentFormula.passCountSql = e.sql2
        } else if (e.type === 'error_result') {
          this.currentFormula.errDataSql = e.sql1
        }
      })
    },
    handleAddForumal: function () {
      this.$router.push({ name: 'formula', params: { add: true } })
    },
    handleDeleteRule: function (record, index) {
      deleteRule(record.id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        this.handleRuleSearch()
      })
    },
    handleDisableRule (record) {
      this.$confirm('此操作将' + (record.enabled === 'Y' ? '禁用' : '启用') + '此规则, 是否继续?', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'
            const data = { enabled: record.enabled === 'Y' ? 'N' : 'Y', id: record.id }
            changeEnabled(data).then((res) => {
              console.log(res)
              if (res.code === 200) {
                const list = []
                this.rules.forEach(e => {
                  if (e.id !== record.id) {
                    list.push(e)
                  } else {
                    e.enabled = res.data.enabled
                    e.lastUpdateByName = res.data.lastUpdateByUserName
                    e.lastUpdateBy = res.data.lastUpdateBy
                    e.lastUpdateTime = res.data.lastUpdateTime
                    list.push(e)
                  }
                })
                this.rules = list
              }
            }).catch((err) => {
              console.log(err)
            }).finally(() => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).then(() => {
        // this.$message({
        //   type: 'success',
        //   message: '操作成功!'
        // });
      }).catch(e => e)// 这个.catch()删除掉就会打印Uncaught (in promise) cancel
    },
    handleCopyRule (record, index) {
      const source = deepCopy(record)
      source.id = null
      this.handleRuleEdit(source, index)
    }
  }
}
</script>
<style lang="less" scoped>
.rule_index_wrapper {
  .ant-dropdown-link {
    font-size: 12px;
  }
}
</style>
